package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/robfig/cron"
	"math/rand"
	"service/basic/config"
	__ "service/basic/proto"
	"service/handler/model"
	"service/untils"
	"strconv"
	"time"
)

type Server struct {
	__.UnimplementedClearServer
}

// 短信发送
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	//限制短信发送
	get := config.Rdb.Get(config.Ctx, "smsCount"+in.Mobile).Val()
	if get == "5" {
		return nil, errors.New("一分钟内最多发送5条")
	}
	init := rand.Intn(9000) + 1000
	//ali := untils.AliYun{}
	//sms, _ := ali.Sms(in.Mobile, strconv.Itoa(init))
	//if *sms.Body.Code != "OK" {
	//	return nil, errors.New(*sms.Body.Message)
	//}

	//将短信存储到redis
	config.Rdb.Set(config.Ctx, "sms"+in.Mobile, init, time.Hour)
	//设置限流机制
	config.Rdb.Incr(config.Ctx, "smsCount"+in.Mobile)
	config.Rdb.Expire(config.Ctx, "smsCount"+in.Mobile, time.Minute)

	return &__.SendSmsResp{
		Message: "短信验证法发送成功",
	}, nil
}

// 注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	var user model.User
	user.Mobile = in.Mobile
	//判断用户是否存在
	if err := user.GetUserInfoByMobile(); err != nil {
		return nil, errors.New("用户查找失败")
	}
	if user.Id != 0 {
		return nil, errors.New("用户已存在")
	}
	//判断验证码
	smsCode := config.Rdb.Get(config.Ctx, "sms"+in.Mobile).Val()
	if smsCode != in.SmsCode {
		return nil, errors.New("验证码错误")
	}
	//注册
	user.Password = untils.MD5(in.Password) //加密
	if err := user.Create(); err != nil {
		return nil, errors.New("注册失败")
	}

	return &__.RegisterResp{
		Id: strconv.Itoa(int(user.Id)),
	}, nil
}

// 登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user model.User
	user.Mobile = in.Mobile
	//判断用户是否存在
	if err := user.GetUserInfoByMobile(); err != nil {
		return nil, errors.New("用户查找失败")
	}
	if user.Id == 0 {
		return nil, errors.New("用户不存在")
	}
	//判断密码
	if user.Password != untils.MD5(in.Password) {
		return nil, errors.New("密码错误")
	}

	return &__.LoginResp{
		Id: strconv.Itoa(int(user.Id)),
	}, nil
}

// 搜索保洁师
func (s *Server) CleanerSearch(_ context.Context, in *__.CleanerSearchReq) (*__.CleanerSearchResp, error) {
	//设置一个等待组
	//var sync sync2.WaitGroup
	var cleaner model.Cleaner
	cleaner.CleanerType = in.CleanerType
	//defer func() {
	//sync.Done()
	if err := cleaner.SearchCleanerType(); err != nil {
		return nil, errors.New("保洁员查询失败")
	}
	//}
	//}()
	//sync.Wait()

	//CronStatus(int64(cleaner.Status)) //定时检测空闲清洁员

	return &__.CleanerSearchResp{
		Id:          int64(cleaner.Id),
		Name:        cleaner.Name,
		Price:       int64(cleaner.Price),
		CleanerType: cleaner.CleanerType,
	}, nil
}

func CronStatus(status int64) {
	c := cron.New()
	spec := "* * */2 * * ?"
	err := c.AddFunc(spec, func() {
		var cleaner model.Cleaner
		cleaner.Status = uint(status)
		if err := cleaner.SearchStatus(); err != nil {
			panic(err)
		}
	})
	fmt.Println(err)
	c.Start()

	select {}
}
